/**
 * JAVACC DEMO 1.0
 * @copy right iussoft company All rights reserved.
 * @Package com.iussoft.portal.send
 */
package com.apache.portal.service;

import java.util.Date;
import java.util.Map;
import java.util.Properties;

import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.AddressException;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;

import org.apache.log4j.Logger;

import com.apache.portal.common.SendService;
import com.apache.portal.common.annotion.AnntationBean;
import com.apache.portal.common.template.FreemarkerHelper;
import com.apache.portal.service.plugin.Uct3SystemPluginImpl;

/**
 * description:  邮件发送接口
 * @author Hou Dayu 创建时间：2016-9-18
 */
@AnntationBean(name = "sendEmail")
public class SendEmailServiceImpl implements SendService {
	private Logger log = Logger.getLogger(Uct3SystemPluginImpl.class);

	public boolean sendMessage(Map<String, String> params) {

		String password = params.get("emailPwd");
		String host = params.get("host");
		String from = params.get("from");

		try {
			Properties props = new Properties();
			props.put("mail.smtp.host", host);
			props.put("mail.smtp.auth", "true");
			Session session = Session.getDefaultInstance(props, null);
			session.setDebug(true);
			MimeMessage message = new MimeMessage(session);
			InternetAddress fromAddress = new InternetAddress(from);
			message.setFrom(fromAddress);
			InternetAddress toAddress = new InternetAddress(params.get("userEmail"));
			message.addRecipient(Message.RecipientType.TO, toAddress);
			message.setSubject(params.get("title"));
			String body = "";
			try {
				body = FreemarkerHelper.instance().getTemplateStr(params, params.get("tempName"));
			} catch (Exception e) {
				return false;
			}
			//message.setText(body);
			message.setContent(body, "text/html;charset=UTF-8"); //发送HTML邮件，内容样式比较丰富  

			log.info("发送主题：" + message.getSubject());
			log.info("发送地址：" + fromAddress);
			log.info("收件地址：" + toAddress);
			log.info("发送内容如下：\n" + body);

			message.setSentDate(new Date());//设置发信时间  
			Transport transport = session.getTransport(params.get("protocol"));
			transport.connect(from, password);
			transport.sendMessage(message, message.getAllRecipients());
			transport.close();
			return true;
		} catch (AddressException e) {
			e.printStackTrace();
		} catch (MessagingException e) {
			e.printStackTrace();
		}
		return false;
	}

}
